import util from '@/lib/util';
import * as types from './mutationTypes';

const actions = {
  /**
   * 获取文件夹列表
   *
   * @param {Function} { commit }
   * @param {Object} { id }
   * */
  fetchFolderList({dispatch, commit}, data) {
    return new Promise(function (resolve, reject) {
      util.ajax.post('/folder/list').then((res) => {
        commit(types.FETCH_FOLDER_LIST, res.data);

        //这里如果当前有激活的目录则，仍在恢复激活状态
        data = data || {folderId: undefined};

        let folderId = -999;
        if (data.folderId) {
          folderId = data.folderId;
        } else if (res.data.length > 0) {
          folderId = res.data[0].folderId;
        }
        if (folderId !== -999) {
          commit(types.CHANGE_FOLDER_ID, folderId);
        }

        resolve(res);
      });
    });


  },
  fetchSearchList({commit}, paramsValue) {
    let params = {
      'pageSize': 10,
      'pageNo': 1

    };

    params = Object.assign({}, params, paramsValue);
    util.ajax.post('/article/search', {...params}).then((res) => {
      if (res.data) {
        // 判断是否返回有值
        if (res.data.list.length < params.pageSize) {
          // 若请求回来数据小于10 则视为到最后一页了
          commit(types.JUDGE_LOADMORE, false);
        }

        //搜索第一页的时候更新总条数
        if (params.pageNo == 1) {
          commit(types.SEARCH_STATE, {searchArticleTotal: res.data.total});
          //搜索的结果第一次加载需要把原来文章列表中的数据清空
          commit(types.CLEAR_ARTICLE_LIST);
        }
        commit(types.FETCH_ARTICLE_LIST, res.data.list);
      }
    });
  },
  changeFolderid({commit}, folderId) {
    commit(types.CHANGE_FOLDER_ID, folderId);
  },
  /**
   * 获取文章列表
   *
   * @param {Function} { commit }
   * @param {Object} [params={}]
   * */
  fetchArticleList({dispatch, commit}, params) {

    return new Promise(function (resolve, reject) {
      commit(types.JUDGE_LOADMORE, true);
      // 开始请求时,编辑区置为false
      commit(types.SHOW_BEGIN_EDITOR_BUTTON, false);
      let paramsValue = {
        'pageSize': 10
      };

      paramsValue = Object.assign({}, paramsValue, params);
      util.ajax.post('/article/list', {...paramsValue}).then((res) => {

        let data = res.data || {list: []};
        let list = data.list || [];

        if (params.pageNo < 2) {
          // 加载第一页时，清空当前文章列表中的数据
          commit(types.CLEAR_ARTICLE_LIST);
          //清空当前文章对象
          commit(types.CLEAR_ARTICLE);
        }
        if (list.length < 10) {
          // 若请求回来数据小于10 则视为没有数据
          commit(types.JUDGE_LOADMORE, false);
        }
        //加载第一页数据，并且有文章数据的情况下，默认激活选中第一篇文章数据
        if (params.pageNo < 2 && list.length > 0) {

          dispatch('activeArticle', list[0].articleId);

        }

        if (!list.length) {
          // 若请求列表为空, 则显示开始写文章button
          commit(types.SHOW_BEGIN_EDITOR_BUTTON, true);
        }
        commit(types.FETCH_ARTICLE_LIST, list);
        resolve(res);
      });
    });
  },
  // 清空文件列表
  clearArticleList({commit}, params) {
    commit(types.CLEAR_ARTICLE_LIST);
  },
  // 清除文章
  clearArticle({commit}, params) {
    commit(types.CLEAR_ARTICLE);
  },
  /**
   * 获取文章详情
   *
   * @param {Function} { commit }
   * @param {Object} [params={}]
   * */
  fetchArticleDetail({commit}, params) {
    return new Promise(function (resolve, reject) {
      util.ajax.post('/article', params).then((res) => {
        if (res.code == 1) {
          commit(types.CHANGE_ARTICLE_ID, params.id);
          commit(types.FETCH_ARTICLE_DETAIL, res.data);
          commit(types.SET_PREVIEW_INFO, {
            title: res.data.title,
            editorHtml: res.data.content, // 带格式
            tags: res.data.articleLabelName,
            ceateTime: res.data.updateTime || res.data.createTime
          });
        }
        resolve(res);
      });
    });
  },
  /**
   * 创建文件夹
   *
   * @param {Function} { commit }
   * @param {String} { url }
   */
  insertFolder({commit}, params) {
    return new Promise(function (resolve, reject) {

      util.ajax.post('/folder/insert', {...params}).then((res) => {
        if (res.code == 1) {
          // 判断是否设置成功
          commit(types.INSERT_FOLDER, res.data);
        }
        resolve(res);
      });

    });
  },
  /**
   * 创建文章(会和保存文章同一个接口)
   *
   * @param {Function} { commit }
   * @param {String} { url }
   */
  insertArticle({commit}, params) {

    commit(types.INSERT_ARTICLE);
    // 清除掉文章
    commit(types.CLEAR_ARTICLE);
  },
  changgeBeginEditorButton({commit}, flag) {
    commit(types.SHOW_BEGIN_EDITOR_BUTTON, flag);
  },
  handleshowPreviewLayer({commit}, data) {
    commit(types.SHOW_PREVIEW_LAYER, data);
  },
  handleShowsetCover({commit}, data) {
    commit(types.SHOW_SET_COVER_LAYER, data);
  },
  clearFolder({commit}, index) {
    // 同时请求下下一篇文章
    commit(types.CLEAR_FOLDER, index);
  },
  deleteArticle({commit}, index) {
    commit(types.DELETE_ARTICLE, index);
  },
  changeFolderName({commit}, param) {
    commit(types.CHANGE_FOLDER_NAME, param);
  },
  clearChoeseImg({commit}) {
    commit(types.CLEAR_CHOOSE_ARTICLE_IMG);
  },
  handleisFromAddImg({commit}, flag) {
    commit(types.IS_FROM_ADD_IMG, flag);
  },
  updateArticlelist({commit}, data) {
    commit(types.UPDATE_ACTICLE_LIST, data);
  },
  /*判断用户是否登录*/
  loginUser({commit}, params) {

    return new Promise(function (resolve, reject) {

      util.ajax.post('loginPost', {...params}).then((res) => {

        commit(types.LOGING_CODE, res.userStatus);
        resolve(res);

      });

    });
  },
  //改变搜索状态数据
  changeSearchState({commit}, params) {
    commit(types.SEARCH_STATE, params);
  },
  changeCropperState({commit}, params) {
    // 操作是否显示裁剪框

    commit(types.CORPPER_IS_SHOW, params);
  },
  activeArticle({dispatch, commit}, article_id) {
    commit(types.ACTIVE_ARTICLE, article_id);
    dispatch('changgeBeginEditorButton', false);
    //激活（选中）一篇文章，更新文章详情对象
    dispatch('fetchArticleDetail', {'id': article_id});
  },
  //改变文件夹中的文章数量
  changeFolderArticleCount({commit}, params) {
    commit(types.CHANGE_FOLDER_COUNT, params);
  },
  haddleSetPreviewInfo({commit}, info) {
    commit(types.SET_PREVIEW_INFO, info);
  },

  /**
   * 新建文章
   *
   * @param {Function} { commit }
   * @param {String} { url }
   */
  newArticle({commit}, params) {
    return new Promise(function (resolve, reject) {
      let paramsValue = {
        'id': '',
        'origContent': '',
        'content': '',
        'title': '请输入文章标题',
        'isDel': '0'
      };
      paramsValue = Object.assign({}, paramsValue, params);
      util.ajax.post(`/article/save`, {...paramsValue}).then((res) => {
        if (res.code == 1) {
          // 判断是否设置成功
          commit(types.NEW_ARTICLE, res.data);


          resolve(res);
        } else {
          reject(res);
        }
      });
    });
  }


};

export default actions;
